import { ApiActionType, LoginForm, LoginToken } from '@/types/data'
import { Dispatch } from "react";
import { LoginAction, RootThunkAction } from '@/types/store'
import request from '@/utils/request'
import { removeToken, setToken } from '@/utils/storage';
export const getLogin=(values:LoginForm):RootThunkAction=>{
 return async(dispatch:Dispatch<LoginAction>)=>{
     const res =await request.post<ApiActionType<LoginToken>>('/authorizations', values)
     console.log(res,'res');
     setToken(res.data.data)
     dispatch({
         type:'login/GET_LOGIN',
         payload:res.data.data
     })
 }
}

export const getCode=(mobile:string):RootThunkAction=>{
 return async()=>{
    await request.get(`/sms/codes/${mobile}`)
    // 注意：验证码是发送到手机上的，因此，不需要更新Redux状态
 }
}

export const Logout =():LoginAction=>{
 removeToken()
 return{
     type:'login/OUT_LOGIN'
 }
}

export function saveToken (token: LoginToken) : LoginAction {
    // 1. 本地持久化
    setToken(token)

    // 2. 保存token
    return {
        type: 'login/token',
        payload: token
    }
}